package com.firefighting.controller;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.firefighting.entity.Contract;
import com.firefighting.entity.MaintenancePlan;
import com.firefighting.entity.PlanListInfo;
import com.firefighting.entity.Task;
import com.firefighting.entity.User;
import com.firefighting.entity.UserBasicInfo;
import com.firefighting.service.BuildingService;
import com.firefighting.service.ContractService;
import com.firefighting.service.InsertUpdateMaintenanceService;
import com.firefighting.service.MaintenancePlanService;
import com.firefighting.service.TaskItemService;
import com.firefighting.service.UserBasicInfoService;
import com.firefighting.service.UserService;

@Controller
@RequestMapping("MaintenancePlan")
public class MaintenancePlanController
{
	@Autowired
	private MaintenancePlanService maintenanncePlanService;
	
	@Autowired
	private ContractService contractService;
	
	@Autowired
	private UserBasicInfoService userBasicInfoService;
	@Autowired
	private BuildingService buildingService;
	/*@Autowired
	private TaskService taskService;*/
	@Autowired
	private TaskItemService taskItemService;
	/*@Autowired
	private MaintenanceplanContentService maintenanceplanContentService;*/
	@Autowired
	private UserService userService;
	@Autowired
	private InsertUpdateMaintenanceService insertUpdateMaintenanceService ;
	
	/**
	 * @author zhyan
	 * @throws IOException 
	 * @throws JsonMappingException 
	 * @throws JsonGenerationException 
	 * @function 展示各维保项目各种计划中未下发/未完成/已完成计划的数量
	 * @date 2018.6.20
	 */
	@RequestMapping("planList")
	private String getMaintenancePlanList(HttpServletRequest request, Model model) throws JsonGenerationException, JsonMappingException, IOException
	{
		User user = (User) request.getSession().getAttribute("currentUser");
		int roleId = user.getRoleid();
		UserBasicInfo userBasicInfo = userBasicInfoService.getInfoByAccount(user.getUsername());
		ObjectMapper objectMapper = new ObjectMapper();
		
		if(roleId == 11)
		{
			//平台管理员，返回所有的列表
			List<PlanListInfo> result = maintenanncePlanService.getPlanListInfo();
			model.addAttribute("content", objectMapper.writeValueAsString(result));
		}
		else if(roleId == 9)
		{
			//消防总队，返回该省的所有列表
			String province = userBasicInfo.getProvince();
			List<Integer> contractIdList = contractService.queryContractIdListByProvince(province);
			//List<HashMap> result = maintenanncePlanService.queryMaintenancePlanListByContractIdList(contractIdList);
			List<PlanListInfo> result = new ArrayList<PlanListInfo>();
			if(contractIdList.size()>0){
				 result = maintenanncePlanService.getPlanListInfoByContractIdList(contractIdList);
			}
			
			model.addAttribute("content", objectMapper.writeValueAsString(result));
		}
		else if(roleId == 10)
		{
			//消防支队，返回该市的所有列表
			
			String province = userBasicInfo.getProvince();
			String city = userBasicInfo.getCity();
			List<Integer> contractIdList = contractService.queryContractIdListByProvinceAndCity(province, city);
			List<PlanListInfo> result = new ArrayList<PlanListInfo>();
			if(contractIdList.size()>0){
				 result = maintenanncePlanService.getPlanListInfoByContractIdList(contractIdList);
			}
			
			model.addAttribute("content", objectMapper.writeValueAsString(result));
		}
		else if(roleId == 2)
		{
			//项目负责人，返回其负责的所有合同的计划列表
			List<PlanListInfo> result = new ArrayList<PlanListInfo>();
			String account = user.getUsername();
			List<Integer> contractIdList = contractService.queryContractIdByProjectLeaderAccount(account);
			if(contractIdList.size()>0){
				 result = maintenanncePlanService.getPlanListInfoByContractIdList(contractIdList);
			}
			
			
			model.addAttribute("content", objectMapper.writeValueAsString(result));
		}
		else if(roleId == 1)
		{
			//企业管理员，返回该企业的所有合同的计划列表
			int enterpriseId = userBasicInfo.getEnterpriseId();
			List<Integer> contractIdList = contractService.queryContractIdListByEnterpriseId(enterpriseId);
			List<PlanListInfo> result = new ArrayList<PlanListInfo>();
			if(contractIdList.size()!=0){
				result = maintenanncePlanService.getPlanListInfoByContractIdList(contractIdList);
			}
			
			
			model.addAttribute("content", objectMapper.writeValueAsString(result));
		}
		
		return "plan/planView";
	}
	
	/**
	 * @author zhyan
	 * @throws IOException 
	 * @throws JsonMappingException 
	 * @throws JsonGenerationException 
	 * @function 查看指定合同中的计划列表
	 * @date 2018.6.20
	 */
	@RequestMapping("planOfContract")
	private String getMaintenancePlanDetail(HttpServletRequest request, Model model) throws JsonGenerationException, JsonMappingException, IOException
	{
		ObjectMapper objectMapper = new ObjectMapper();
		int id = Integer.parseInt(request.getParameter("id"));
		//System.out.println("id = " + id);
		//int contractId = maintenanncePlanService.selectContractIdByPlanId(id);
		
		@SuppressWarnings("rawtypes")
		List<HashMap> result = maintenanncePlanService.queryPlanInfoByContractId(id);
		Contract contract = contractService.queryContract(id);
		
		model.addAttribute("content", objectMapper.writeValueAsString(result));
		model.addAttribute("contract",contract);
		model.addAttribute("contractId",id);
		return "plan/projectPlan";
	}
	
	/**
	 * @author zhyan
	 * @function 删除合同中的计划
	 * @date 2018.6.20
	 */
	@RequestMapping("deletePlan")
	private String deletePlan(HttpServletRequest request, Model model)
	{
		int id = Integer.parseInt(request.getParameter("id"));
		boolean isDeleted = maintenanncePlanService.isDeletePlan(id);
		
		if(isDeleted)
		{
			model.addAttribute("content","true");//删除成功返回true
		}
		else
		{
			model.addAttribute("content", "false");//删除失败返回false
		}
		
		return "plan/projectPlan";
	}
	//Hanjd
		//下发计划1-查询计划中维保项目列表
		@RequestMapping("getMaintenanceList")
		private String getMaintenanceList(HttpServletRequest request, Model model)
		{
			System.out.println("id----"+request.getParameter("id"));
			Integer planId = Integer.valueOf(request.getParameter("id"));
			Integer contractId = Integer.valueOf(request.getParameter("contractid"));
			System.out.println("contractId  "+contractId);
			MaintenancePlan maintenancePlan = new MaintenancePlan();
			maintenancePlan = maintenanncePlanService.queryByMantenancePlanId(planId);
			String planName = maintenancePlan.getPlanName();
			Contract contract = contractService.queryContract(maintenancePlan.getContractId());
			String projectName = contract.getProjectName();
			List<UserBasicInfo> nameList = new ArrayList<UserBasicInfo>();
			User user = (User) request.getSession().getAttribute("currentUser");
			String username = user.getUsername();
			int enterpriseId = userBasicInfoService.queryEnterpriseIdByUsername(username);
			String  type =null;
			switch (maintenancePlan.getPlanType()) {
			case 1:
				type = "月";
				break;
			case 2:
				type = "季";
				break;
			case 3:
				type = "年";
				break;

			default:
				break;
			}
			
			List<HashMap<String, Object>> buildingList = buildingService.selectBuildingList(maintenancePlan.getContractId());
			System.out.println("buildingList------"+buildingList);
			nameList = userBasicInfoService.getRoleInfoByEnter(enterpriseId,3);
			model.addAttribute("nameList",nameList);
			model.addAttribute("buildingList", buildingList);
			model.addAttribute("planName", planName);
			model.addAttribute("type", type);
			model.addAttribute("planId", planId);
			model.addAttribute("projectName", projectName);
			model.addAttribute("contractId", contractId);
			return "plan/makePlan";//展示列表
		}
		
		//Hanjd
		//下发计划1-按建筑物查询计划中维保项目列表
		@RequestMapping(value="searchMaintenancePlanList", produces = "text/html;charset=UTF-8")
		@ResponseBody
		private String searchMaintenancePlanList(HttpServletRequest request, Model model) throws JsonGenerationException, JsonMappingException, IOException
		{
			
			Integer planId = Integer.valueOf(request.getParameter("planId"));
			Integer buildingId = Integer.valueOf(request.getParameter("buildingId"));

			List<UserBasicInfo> nameList = new ArrayList<UserBasicInfo>();
			User user = (User) request.getSession().getAttribute("currentUser");
			String username = user.getUsername();
			int enterpriseId = userBasicInfoService.queryEnterpriseIdByUsername(username);
			List<HashMap<String, Object>> result1 = new ArrayList<HashMap<String,Object>>();
			result1 = maintenanncePlanService.selectMaintenanceList(planId,buildingId);
			List<HashMap<String, Object>> result2 = new ArrayList<HashMap<String,Object>>();
			System.out.println("planId"+planId+"buildingId"+buildingId);
			result2 = maintenanncePlanService.selectBuildingAlreadyMaintenanceList(planId,buildingId);
			System.out.println("result1----"+result1);
			System.out.println("result2----"+result2);
			
			
			@SuppressWarnings("unused")
			ObjectMapper objectMapper = new ObjectMapper();
			for(HashMap<String, Object>hashMap:result1){
				
				String executor = "";
				String building_name = "";
				Object execute_time ="";
				int mtId = 0;
				int contentId = 0;
				for (HashMap.Entry<String, Object> m : hashMap.entrySet()) {
					
					if (m.getKey().equals("mtId")) {//如果拿到维保内容id
						
						mtId = (Integer) m.getValue();
						
						/*List<Integer> contentIdInTaskOfBuilding = taskItemService.getcontentIdInTaskOfBuildingPlan(planId, buildingId);//查询建筑物已下发的contentID
//						System.out.println("contentIdInTaskOfBuilding"+contentIdInTaskOfBuilding);
						if(contentIdInTaskOfBuilding.contains(mtId)){//如果该计划内的建筑已经将该内容下发
							hashMap.put("development", "已下发");
						}else{
							hashMap.put("development", "未下发");
						}
						List<Integer> finishContentIdInTaskOfBuilding = taskItemService.getfinishContentIdInTaskOfBuildingPlan(planId, buildingId);//查询建筑物已完成的contentID
//						System.out.println("contentIdInTaskOfBuilding"+contentIdInTaskOfBuilding);
						if(finishContentIdInTaskOfBuilding.contains(mtId)){//如果该计划内的建筑已经将该内容完成
							hashMap.put("state_finished", "已完成");
						}else{
							hashMap.put("state_finished", "未完成");
						}*/
						
						//遍历 resuilt2 将内容插入 resuilt1
						for(HashMap<String, Object>hMap:result2){
							
							
							for (HashMap.Entry<String, Object> mp : hMap.entrySet()) {//拿到 resuilt2 维保内容id

								if (mp.getKey().equals("contentId")) {
									contentId = (Integer) mp.getValue();
								}
									
							}
								
							if (mtId == contentId && mtId != 0 && contentId != 0){//如果 mtId == contentId  且不为零  拿执行人、建筑物名称
								
								for (HashMap.Entry<String, Object> mp : hMap.entrySet()) {

									if (mp.getKey().equals("executor")) {
										executor = (String) mp.getValue();
									}
									if (mp.getKey().equals("building_name")) {
										building_name = (String) mp.getValue();
									}
									if (mp.getKey().equals("execute_time")) {
										execute_time =  mp.getValue();
									}
										
								}
								
								
				            }
							
						}
					}else continue;
					
					
					
	            }
//				System.out.println("mtId"+mtId+"+contentId---"+contentId + "   executor---"+executor+ "  building_name---"+building_name+"  execute_time---"+execute_time);
				hashMap.put("execute_time", execute_time);
				hashMap.put("executor", executor);
				hashMap.put("building_name", building_name);
                
			}
			System.out.println("result1----"+result1);
			String json = JSONArray.toJSONString(result1);
			nameList = userBasicInfoService.getRoleInfoByEnter(enterpriseId,3);
			model.addAttribute("nameList",nameList);
				
			return json;//展示列表,ajax返回string即可
		}
		//Hanjd
		//下发计划2-下发计划中维保项目列表
		@RequestMapping("developmentPlan")
		@ResponseBody
		private String developmentPlan(HttpServletRequest request, Model model)
		{

//			JSONObject result=new JSONObject();
			Map<String,Object> map = new HashMap<String,Object>();
			Integer buildingId = Integer.valueOf(request.getParameter("buildingId"));
			Integer planId = Integer.valueOf(request.getParameter("id"));
			SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");//设置日期格式
			MaintenancePlan maintenancePlan = new MaintenancePlan();
			maintenancePlan = maintenanncePlanService.queryByMantenancePlanId(planId);
			String planName = maintenancePlan.getPlanName();
			Integer undelivered = maintenancePlan.getUndeliveredNumber();
			Contract contract = new Contract();
			contract = contractService.queryContractByContractID(maintenancePlan.getContractId());
			
			String maintence = request.getParameter("params");
			Integer executorName = Integer.valueOf(request.getParameter("personId"));
			int executorId = userService.getUserIdByUserBasicId(executorName);
/*			System.out.println("executorId---"+executorId);
			System.out.println("maintence---"+maintence);
			System.out.println("building---"+buildingId);
			System.out.println("executorName---"+executorName);*/
			JSONArray jsonArray = JSONArray.parseArray(maintence);
		/*	System.out.println(jsonArray.toJSONString());*/
			JSONObject jsonOne = null;
			if (jsonArray.size()==0) {
				map.put("flag", "2");
				return JSONObject.toJSONString(map);
			}
			else if (jsonArray.size()>0) {
				for (int i = 0; i < jsonArray.size(); i++) {
					jsonOne = jsonArray.getJSONObject(i);
					System.out.println("date----"+jsonOne.getString("date"));
					if (jsonOne.getString("date").equals("") ) {
						System.out.println("flag----"+2);
//						result.put("flag", 2);
//						result.put("success", true);
//						result.put("errorMsg", "有时间未选择");
						map.put("flag", "2");
						return JSONObject.toJSONString(map);
//						return "redirect:/MaintenancePlan/searchMaintenancePlanList.htm?planId="+planId+"&buildingId="+buildingId;
					}
				}
				@SuppressWarnings("unused")
				//插入一条新的task
				UserBasicInfo userBasicInfo = new UserBasicInfo();
				Task task = new Task();
				task.setMaintenanceplanId(planId);
				task.setAppIdAccount(executorId);
				task.setType("测试");
				task.setName(planName+df.format(new Date()));
				task.setCharacter("计划内");
				task.setLocation(contract.getAddress());
				task.setMaintenanceProject(contract.getId());
				task.setEnterprise(contract.getMaintenanceEnterpriseId());
				task.setCreateTime(new Date());
				task.setStatus("待接收");
				task.setBuildingId(buildingId);
				//更改maintenancePlan里面的未下发项目内容数
				maintenancePlan.setStateFinished("未完成");
				undelivered = undelivered-jsonArray.size();
				maintenancePlan.setUndeliveredNumber(undelivered);
				
				
				insertUpdateMaintenanceService.InsertUpdateMaintenance(task, maintenancePlan, jsonArray, planId,buildingId);
				
				
				
			}
			map.put("flag", "1");
//			return "redirect:/MaintenancePlan/searchMaintenancePlanList.htm?planId="+planId+"&buildingId="+buildingId;
//			return "plan/makePlan";
			return JSONObject.toJSONString(map);
				
		}
}